package com.gszy.auth.security;

import com.gszy.auth.entity.Permission;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class AuthorizationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestUri = request.getRequestURI().replace(request.getContextPath(), "");
        if (ExcludedUrlConfiguration.getInstance().isUrlExcluded(requestUri)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //---------授权---------------
        UserDetails userDetails = SecurityContextHolder.getInstance().getUserDetails();
        List<Permission> authorities = userDetails.getAuthorities();
        boolean isAuthorized = false;
        for (Permission permission:authorities){

            if (requestUri.equals(permission.getUrl())){
                isAuthorized = true;
            }
        }
        if (isAuthorized){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            request.setAttribute("msg","权限不足！请联系管理员添加权限...");
            request.getRequestDispatcher("/pages/failer.jsp").forward(request,response);
        }

        //---------------------------



    }

    @Override
    public void destroy() {

    }
}
